//
//  SEInspListVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2022/12/10.
//
// 【首页-维保服务】维修工程师-巡检记录

import Foundation
import UIKit

class SEInspListVC: SubLevelViewController, PullToRefreshPresentable {
    let listV = InspListView()
    let bottomV = UIView()
    let segmentedC = BSSegmentedControl()
    
    var datas : [ParListModal?] = []

    var param = ParFormParam(pageSize: PageSize)
    var c_param = CountParam()

    var pageNum: Int = 1
    var totalPage: Int64 = 0

    var yearMonth: String = ""

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "巡检记录"
        view.backgroundColor = .bg
        NotificationCenter.default.addObserver(self, selector: #selector(reloadData), name: NotiInsp, object: nil)

        setupPullToRefresh(on: listV.seTable.tableView)

        if deptName == nil {
            deptName = BSUser.currentUser.deptName
            deptId = BSUser.currentUser.deptId
        }
        
        if yearMonth == "" {
            yearMonth = "\(date.momentYear())-\(date.momentMonth())"
        }
        
        let start = "\(yearMonth)-01"
        listV.dateCtl.month = start.momentMonth()
        listV.dateCtl.year = start.momentYear()

        let end = Date.endOfMonth(date: start.moment())

        param.startTime = start.moment().momentTimeZero()
        param.endTime = end.momentTimeEnd()
        
        c_param.startTime = start
        c_param.endTime = end.elTodayDate()
        
        param.dictLabel = wbtype
        param.type = "1" // 总行/分行/支行/网点都为空，工程师传0：我的巡检；1是巡检列表
        
        c_param.tmplValue = wbtype
        setupNavItems()
        setupUI()
        reloadData()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navBarStyle(.white)
    }
    
    deinit {
        listV.seTable.tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        getList()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        getList()
    }
    
    func segmentedTapped(_ index: Int) {
        if index == 0 { // 巡检任务
            param.type = "1"
            listV.seTable.datas = []
            pageNum = 1
            reloadData()
        } else if index == 1 { // 我的巡检
            param.type = "0"
            listV.seTable.datas = []
            pageNum = 1
            reloadData()
        }
    }
    
    @objc func reloadData() {
        pageNum = 1
        /// 维保服务-巡检记录
        getList()
        
        /// 巡检记录-网点-头部红色
        API.getCountPatrolPatr(withParam: c_param) { responseModel in
            DispatchQueue.main.async {
                self.listV.summaryV.update(withData: responseModel.model)
            }
        }
    }
    
    func getList() {
        param.pageNum = pageNum
        view.showToastActivity()
        /// 维保服务-巡检记录
        API.getParFromList(withParam: param) { responseModel in
            self.view.hideToastActivity()
            if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                self.pageNum -= 1
                return
            }
            if self.pageNum == 1 {
                self.datas.removeAll()
            }
            self.totalPage = responseModel.totalPage
            self.datas.append(contentsOf: responseModel.models ?? [])
            DispatchQueue.main.async {
                self.listV.seTable.datas = self.datas
            }
        }
    }
    
    @objc func searchTapped() {
        let bSearchVC = BranchSearchVC()
        bSearchVC.didSelectBranchWith = { (dept, _) -> () in
            self.deptName = dept.deptName
            self.deptId = dept.deptId
            self.param.deptid = dept.deptId
            self.c_param.deptId = dept.deptId
            self.title = "\(dept.deptName ?? "")维保记录"
            self.reloadData()
            bSearchVC.navigationController?.popViewController(animated: true)
        }
        navigationController?.pushViewController(bSearchVC, animated: true)
    }
    
    func setupUI() {
        bottomV.backgroundColor = .white
        view.addSubview(bottomV)
        bottomV.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(56 + UIDevice.safeBottom())
        }
        
        let line = UIView()
        line.backgroundColor = .hex("#F2F2F2")
        bottomV.addSubview(line)
        line.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(0.5)
        }
        
        bottomV.addSubview(segmentedC)
        segmentedC.snp.makeConstraints { make in
            make.top.equalTo(bottomV.snp.top).offset(10)
            make.left.equalTo(bottomV.snp.left).offset(22)
            make.right.equalTo(bottomV.snp.right).offset(-22)
            make.height.equalTo(36)
        }
        segmentedC.itemTitles = ["巡检任务", "我的巡检"]
        segmentedC.currentSelectedIndex = 0
        segmentedC.didSelectItemWith = { (index, title) -> () in
            self.segmentedTapped(index)
        }
        
        listV.seTable.needReload = { () -> () in
            self.param.pageNum = 1
            self.reloadData()
        }
        listV.statusCtl.didSelectItemWith = { (index, modal) -> () in
            self.listV.statusCtl.key = "状态（\(modal.name)）"
            self.param.status = modal.id
            self.param.pageNum = 1
            self.reloadData()
        }
        listV.dateCtl.didSelectYearMonthWith = { (ym) -> () in
            let sDateStr = "\(ym)-01"
            let eDateStr = Date.endOfMonth(date: sDateStr.moment())
            
            self.param.startTime = sDateStr.moment().momentTimeZero()
            self.param.endTime = eDateStr.momentTimeEnd()
            
            self.c_param.startTime = sDateStr
            self.c_param.endTime = eDateStr.elTodayDate()

            self.param.pageNum = 1
            self.reloadData()
        }
        view.addSubview(listV)
        listV.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(bottomV.snp.top)
        }
    }
    
    func setupNavItems() {
        let searchBtn = UIButton(type: .custom)
        searchBtn.setImage(UIImage(named: "ic_search"), for: .normal)
        searchBtn.addTarget(self, action: #selector(searchTapped), for: .touchUpInside)
        searchBtn.frame = CGRect(x: 0, y: 0, width: 44, height: 44)
        searchBtn.contentEdgeInsets = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 0)
        let searchBar = UIBarButtonItem(customView: searchBtn)

        navigationItem.rightBarButtonItems = [searchBar]
    }
}
